package com.mall.common.service.impl;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.mall.common.dao.S_deptDao;
import com.mall.common.domain.manage.S_deptDomain;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.S_deptService;

/**
 * Service实现类 - 部门
 */
@Service
@Transactional(readOnly=true)
public class S_deptServiceImpl extends BaseServiceImpl<S_deptDomain, Long>
		implements S_deptService {

	@Resource
	public void setBaseDao(S_deptDao s_deptDao) {
		super.setBaseDao(s_deptDao);
	}	
	
	/**
	 * 获取菜单树，会递归查询所有子菜单
	 */
	@Override
	@Transactional(readOnly=true)
	public List<S_deptDomain> getDeptTree(Long parentId, Long[] deptIds) {
		Assert.notNull(parentId, "parentId is required");
		
		List<S_deptDomain> deptList = null;
		
		S_deptDomain upDomain = this.find(parentId);
		
		if(deptIds != null && deptIds.length > 0){
			String hql = "select m from S_deptDomain bean where bean.id in (:deptIds)";
			getEntityManager().createQuery(hql).setParameter("deptIds", Arrays.asList(deptIds));
		} else {
			Finder f = Finder.create("from S_deptDomain bean");
			f.append(" where bean.code like CONCAT(:up_code, '%')");
			f.setParam("up_code", upDomain.getCode());
			deptList = f.findHQLList();
		}
		return deptList;
	}
	
	@Override
	public List<S_deptDomain> getTopList(){
		Finder f = getTopFinder();
		return f.findHQLList();
	}
	
	@Override
	public List<S_deptDomain> getTopListByRigth(Long[] deptIds) {
		Finder f = Finder.create("select bean from S_deptDomain bean");
		f.append(" where bean in (:deptIds)");
		f.setParamList("deptIds", deptIds);
		f.append(" and bean.parent.id is null");
		f.append(" order by bean.priority asc,bean.id asc");
		return f.findHQLList();
	}
			
	private Finder getTopFinder() {
		Finder f = Finder.create("from S_deptDomain bean");
		f.append(" where bean.upDomain.id is null");
		return f;
	}
}